package com.moon.interface_api.utils;

import net.sf.json.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

/**
 * Created by Administrator on 2016/3/2 0002.
 */
public class HttpUtils {

    private static Logger logger = LoggerFactory.getLogger(HttpUtils.class);
    private static RestTemplate restTemplate;

    static {
        if (restTemplate == null) {
            restTemplate = new RestTemplate();
        }
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent","Mozilla/5.0 ( ; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1");
            conn.setRequestProperty("Accept-Language","zh-CN,zh;q=0.9");
            conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
            conn.setRequestProperty("charset","UTF-8");
            conn.setRequestProperty("Host","jie.yoyosay.cn");
            conn.setRequestProperty("Origin","http://jie.yoyosay.cn");
            conn.setRequestProperty("Referer","http://jie.yoyosay.cn/ajax/regist?s=gj388");
            conn.setRequestProperty("X-Requested-With","XMLHttpRequest");
            conn.setRequestProperty("Access-Control-Allow-Headers","Content-Type,Authorization");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    public static String ZSPost(String url, String param,  Map<String,String> map) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
            conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
            conn.setRequestProperty("Accept-Language","zh-CN,zh;q=0.9");
            conn.setRequestProperty("Connection","keep-alive");
            conn.setRequestProperty("Cookie","JSESSIONID="+map.get("JSESSIONID"));
            System.out.println(map.get("JSESSIONID"));
            conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
            conn.setRequestProperty("Host","www.pengbin.xyz");
            conn.setRequestProperty("Origin","http://www.pengbin.xyz");
            conn.setRequestProperty("Referer","http://www.pengbin.xyz/smater/?keyfrom=463&uuid=1401369587");
            conn.setRequestProperty("User-Agent","Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1");
            conn.setRequestProperty("X-Requested-With","XMLHttpRequest");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    private static MultiValueMap<String, String> initParameterMap(Map<String, Object> params) {
        if (params != null && params.size() > 0) {
            MultiValueMap<String, String> mparams = new LinkedMultiValueMap<String, String>();
            Iterator<String> it = params.keySet().iterator();
            while (it.hasNext()) {
                String key = it.next();
                mparams.add(key, StringUtil.toString(params.get(key)));
            }
            return mparams;
        } else {
            return null;
        }
    }

    private static HttpHeaders initHeader(Map<String, Object> params) {
        if (params != null && params.size() > 0) {
            HttpHeaders requestHeaders = new HttpHeaders();
            for (String key : params.keySet()) {
                requestHeaders.add(key,  StringUtil.toString(params.get(key)));
            }
            return requestHeaders;
        } else {
            return null;
        }
    }

    /**
     * 加密解密的参数
     *
     * @param url
     * @param params
     * @return
     */
    public static String post(String url, Map<String, Object> params) {
        return restTemplate.postForObject(url, initParameterMap(params), String.class);
    }

    /**
     * 不需要参数
     *
     * @param url
     * @return
     */
    public static String post(String url) {
        return post(url, null);
    }

    public static String get(String url) {
        return restTemplate.getForObject(url, String.class);
    }

    public static String commonPost(String url, String param,  Map<String,String> header) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            if(header != null){
                for (String key : header.keySet()) {
                    conn.setRequestProperty(key,header.get(key));
                }  
            }
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }
    
    
    public static HttpResponse commonGet(String url, Map<String,String> header){
        HashMap<String, String> jsonid = new HashMap<>();
        /*urlNameString=urlNameString.replace("TOKEN", token);
        urlNameString=urlNameString.replace("OPENID",openid);*/
        try {
            // 根据地址获取请求
            HttpGet request = new HttpGet(url);//这里发送get请求
            if (header != null){
                for (String key : header.keySet()) {
                    request.addHeader(key,header.get(key));
                }
            }
            // 获取当前客户端对象
            HttpClient httpClient = new DefaultHttpClient();
            // 通过请求对象获取响应对象
            HttpResponse response = httpClient.execute(request);
            /*Header firstHeader = response.getFirstHeader("Set-Cookie");
            String value = firstHeader.getValue();
            String s = value.split(";")[0];
            String s1 = s.split("=")[1];
            Cookie cookie = new Cookie("JSESSIONID",s1);
            cookie.setPath("/");
            cookie.setHttpOnly(true);
            jsonid.put("JSESSIONID",s1);
            //res.addCookie(cookie);*/
            return response;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Map<String, String> getImageStrFromUrl(String imgURL,Map<String,String> header) {
        
        HashMap<String, String> Result = new HashMap<>();
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        try {
            // 创建URL
            URL url = new URL(imgURL);
            byte[] by = new byte[1024];
            // 创建链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            if(header != null){
                for (String key : header.keySet()) {
                    conn.addRequestProperty(key,header.get(key));
                }
            }
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            InputStream is = conn.getInputStream();
            // 将内容读取内存中
            int len = -1;
            while ((len = is.read(by)) != -1) {
                data.write(by, 0, len);
            }
           /* Map<String, List<String>> headerFields = conn.getHeaderFields();
            for (String s : headerFields.keySet()) {
                if("Set-Cookie".equals(s)){
                    List<String> strings = headerFields.get("Set-Cookie");
                    for (String string : strings) {
                        String JSESSIONID = string.split(";")[0].split("=")[1];
                        Result.put("JSESSIONID",JSESSIONID);
                        System.out.println("图片"+JSESSIONID);
                    }
                    System.out.println(strings);
                }
            }
            Result.put("JSESSIONID",map.get("JSESSIONID"));*/
            // 关闭流
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        String pics = encoder.encode(data.toByteArray());
        Result.put("img",pics);
        return Result;
    }

    
    /*public ServiceReturnModel showPhotos(@RequestBody Map<String,String> params,
                                         HttpServletRequest request,
                                         HttpServletResponse response) {
        String imagePath = params.get("fileName");
        response.reset();
        try {
            FileSystemResource fileSystemResource = new FileSystemResource(imagePath);
            OutputStream output = response.getOutputStream();
            if (imagePath.toLowerCase().endsWith(".png") || imagePath.toLowerCase().endsWith(".jpg")) {
                response.setContentType("image/jpeg");// 设定输出的类型
                InputStream imageIn = fileSystemResource.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(imageIn);// 输入缓冲流
                BufferedOutputStream bos = new BufferedOutputStream(output);// 输出缓冲流
                byte data[] = new byte[4096];// 缓冲字节数
                int size = 0;
                size = bis.read(data);
                while (size != -1) {
                    bos.write(data, 0, size);
                    size = bis.read(data);
                }
                bis.close();
                bos.flush();// 清空输出缓冲流
                bos.close();
            }
            output.close();
        } catch (IOException e) {
            //return getResultData(new ServiceReturnModel(), new JsonHeadModel(getSerialNo(request), "查询图片不存在"), null);
            return ServiceReturnModel.toFailedResult("1111","操作失败");
        }
        return null;
    }

    protected String getResultData(ServiceReturnModel serviceReturnModel, JsonHeadModel headModel, Object obj) {
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
        JsonBackModel model;
        if ("FAILD".equals(serviceReturnModel.getStatus())) {
            headModel.setStatus("FAILD");
            headModel.setCode(serviceReturnModel.getCode());
            headModel.setMemo(serviceReturnModel.getMemo());
            model = new JsonBackModel("", headModel);
            return JSONObject.fromObject(model, jsonConfig).toString();
        } else {
            model = new JsonBackModel(obj == null ? "" : obj, headModel);
            return JSONObject.fromObject(model, jsonConfig).toString();
        }
    }



    protected String getSerialNo(HttpServletRequest request) {
        String serialNo = (String)request.getAttribute("serialNo");
        return serialNo;
    }*/

    public static String postForJson(String url,Map<String,Object> params){

        HttpPost httpPost = new HttpPost(url);
        CloseableHttpClient client = HttpClients.createDefault();
        String respContent = null;

        //        json方式
        JSONObject jsonParam = new JSONObject();
        jsonParam.putAll(params);
        StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8");//解决中文乱码问题    
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        System.out.println();


        //        表单方式
        //        List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>(); 
        //        pairList.add(new BasicNameValuePair("name", "admin"));
        //        pairList.add(new BasicNameValuePair("pass", "123456"));
        //        httpPost.setEntity(new UrlEncodedFormEntity(pairList, "utf-8"));   


        try {
            HttpResponse resp = client.execute(httpPost);
            if(resp.getStatusLine().getStatusCode() == 200) {
                org.apache.http.HttpEntity entity1 = resp.getEntity();
                respContent = EntityUtils.toString(entity1,"UTF-8");
            }
        }catch (Exception e){
            return "调用失败";
        }
        return respContent;
    }

    /**
     *@Author:chengliang
     *@date 2018/12/25_9:16
     *@param 
     *@return 
     * 表单方式 post请求  不行
     */
    public static String postForForm(String url,Map<String,Object> params){

        HttpPost httpPost = new HttpPost(url);
        CloseableHttpClient client = HttpClients.createDefault();
        String respContent = null;
        try {
            List<BasicNameValuePair> pairList = new ArrayList<>();
            //添加参数
            for (String key : params.keySet()) {
                pairList.add(new BasicNameValuePair(key, params.get("key").toString())); 
            }
            httpPost.setEntity(new UrlEncodedFormEntity(pairList, "utf-8"));
            HttpResponse resp = client.execute(httpPost);
            if(resp.getStatusLine().getStatusCode() == 200) {
                org.apache.http.HttpEntity entity1 = resp.getEntity();
                respContent = EntityUtils.toString(entity1,"UTF-8");
            }
        }catch (Exception e){
            return "调用失败";
        }
        return respContent;
    }

    public static boolean GenerateImage(String imgStr)
    {   //对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) //图像数据为空
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        try
        {
            //Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            for(int i=0;i<b.length;++i)
            {
                if(b[i]<0)
                {//调整异常数据
                    b[i]+=256;
                }
            }
            //生成jpeg图片
            String imgFilePath = "d://222.jpg";//新生成的图片
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();
            return true;
        }
        catch (Exception e)
        {
            return false;
        }
    }

    public static String openTxtFile(String filePath) {
        int HttpResult; // 服务器返回的状态
        String ee = new String();
        try
        {
            URL url =new URL(filePath); // 创建URL
            URLConnection urlconn = url.openConnection(); // 试图连接并取得返回状态码
            urlconn.connect();
            HttpURLConnection httpconn =(HttpURLConnection)urlconn;
            HttpResult = httpconn.getResponseCode();
            if(HttpResult != HttpURLConnection.HTTP_OK) {
                System.out.print("无法连接到");
            } else {
                int filesize = urlconn.getContentLength(); // 取数据长度
                InputStreamReader isReader = new InputStreamReader(urlconn.getInputStream(),"UTF-8");
                BufferedReader reader = new BufferedReader(isReader);
                StringBuffer buffer = new StringBuffer();
                String line; // 用来保存每行读取的内容
                line = reader.readLine(); // 读取第一行
                while (line != null) { // 如果 line 为空说明读完了
                    buffer.append(line); // 将读到的内容添加到 buffer 中
                    buffer.append(" "); // 添加换行符
                    line = reader.readLine(); // 读取下一行
                }
                System.out.print(buffer.toString());
                ee = buffer.toString();
            }
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return  ee;
    }

  public static String sendGet(String url, String param) {
    String result = "";
    BufferedReader in = null;
    HttpURLConnection connection = null;
    try {
      String urlNameString="";
      if(url.contains("?")){
        urlNameString = url + "&" + param;
      }
      else{
        urlNameString = url + "?" + param;
      }

      URL realUrl = new URL(urlNameString);
      if (url.startsWith("https")) {
        connection = (HttpsURLConnection)realUrl.openConnection();
      } else {
        connection = (HttpURLConnection)realUrl.openConnection();
      }
      connection.setRequestMethod("GET");
      connection.setReadTimeout(30000);
      connection.setConnectTimeout(30000);

      connection.setDoInput(true);
      connection.connect();
      Map<String, List<String>> map = connection.getHeaderFields();
//      for (String key : map.keySet()) {
//        System.out.println(key + "--->" + map.get(key));
//      }
      if("403".equals(connection.getResponseCode())){
        return "403";
      }
      InputStream reader =connection.getInputStream();
      if(reader!=null){
        in = new BufferedReader(new InputStreamReader(reader));
        String line;
        while ((line = in.readLine()) != null)
        {
          result = result + line;
        }
      }else{
        result=connection.getResponseCode()+"";
      }
    }catch (Exception e){
      System.out.println("发送GET请求出现异常！" + e);
      e.printStackTrace();
      try{
        if (in != null) {
          in.close();
        }
      }catch (Exception e2){
        e2.printStackTrace();
      }
    }finally{
      try{
        if (in != null) {
          in.close();
        }
      }catch (Exception e2){
        e2.printStackTrace();
      }
    }
    return result;
  }

}
